import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:hospitable_rental/routes/routes.dart';
import 'package:hospitable_rental/utils/common_toast.dart';
import 'package:hospitable_rental/utils/dio_http.dart';
import 'package:hospitable_rental/utils/utils.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({Key? key}) : super(key: key);

  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  bool _showPsd = false;
  bool _showRepsd = false;

  late TextEditingController _username;
  late TextEditingController _password;
  late TextEditingController _repassword;

  @override
  void initState() {
    _username = TextEditingController();
    _password = TextEditingController();
    _repassword = TextEditingController();
    super.initState();
  }

  @override
  void dispose() {
    _username.dispose();
    _password.dispose();
    _repassword.dispose();
    super.dispose();
  }

  _registerHandler() async {
    var username = _username.text;
    var password = _password.text;
    var repassword = _repassword.text;

    if (password != repassword) {
      CommonToast.showToast("两次输入密码不一致");
      return;
    }

    if (stringIsNullOrEmpty(username) || stringIsNullOrEmpty(password)) {
      CommonToast.showToast("用户名或密码不能为空");
      return;
    }

    var result = await DioHttp.of(context).post(
      "/register",
      params: {
        "username": username,
        "password": password,
      },
    );

    var data = json.decode(result.toString());

    print(data);

    int code = data["data"]["code"];
    String message = data["message"].toString();

    CommonToast.showToast(message);

    if (code == 0) {
      Navigator.of(context).pushReplacementNamed(Routes.login);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("注册"),
      ),
      body: SafeArea(
        minimum: EdgeInsets.all(30.0),
        child: SingleChildScrollView(
          child: Form(
            child: Column(
              children: [
                _getUsernameWidget(),
                SizedBox(height: 8.0),
                _getPasswordWidget(),
                SizedBox(height: 8.0),
                _getRepasswordWidget(),
                SizedBox(height: 50.0),
                _getRegisterButtonWidget(),
                _getLoginWidget(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _getUsernameWidget() {
    return TextFormField(
      controller: _username,
      decoration: InputDecoration(
        labelText: "用户名",
        hintText: "请输入用户名",
        icon: Icon(Icons.person),
      ),
      textInputAction: TextInputAction.next,
    );
  }

  Widget _getPasswordWidget() {
    return TextFormField(
      controller: _password,
      decoration: InputDecoration(
          labelText: "密码",
          hintText: "请输入密码",
          icon: Icon(Icons.lock),
          suffixIcon: IconButton(
            icon: Icon(_showPsd ? Icons.visibility_off : Icons.visibility),
            onPressed: () => setState(() => _showPsd = !_showPsd),
          )),
      obscureText: !_showPsd,
      textInputAction: TextInputAction.next,
    );
  }

  Widget _getRepasswordWidget() {
    return TextFormField(
      controller: _repassword,
      decoration: InputDecoration(
          labelText: "确认密码",
          hintText: "请输入密码",
          icon: Icon(Icons.lock),
          suffixIcon: IconButton(
            icon: Icon(_showRepsd ? Icons.visibility_off : Icons.visibility),
            onPressed: () => setState(() => _showRepsd = !_showRepsd),
          )),
      obscureText: !_showRepsd,
      textInputAction: TextInputAction.done,
    );
  }

  Widget _getRegisterButtonWidget() {
    return Container(
      width: double.infinity,
      height: 50.0,
      child: ElevatedButton(
        child: Text("注 册"),
        onPressed: _registerHandler,
      ),
    );
  }

  Widget _getLoginWidget() {
    return Container(
      width: double.infinity,
      height: 50.0,
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text("已有账号，"),
          TextButton(
            child: Text("去登录~"),
            onPressed: _login,
          )
        ],
      ),
    );
  }

  void _login() {
    Navigator.pushReplacementNamed(context, Routes.login);
  }
}
